namespace Terra.Core.Common.ErrorCodes.Extensions;

using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Terra.Core.Common.ErrorCodes.Options;
using Terra.Core.Common.ErrorCodes.Providers;
using Terra.Core.Common.ErrorCodes.Registration;

/// <summary>
/// 错误码服务扩展
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 添加错误码服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddErrorCodes(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        // 注册配置
        services.Configure<ErrorCodeOptions>(configuration.GetSection("ErrorCodes"));

        // 注册错误码提供者
        services.AddSingleton<IErrorCodeProvider, DefaultErrorCodeProvider>();

        // 注册错误码初始化器
        services.AddHostedService<ErrorCodeInitializer>();

        return services;
    }

    /// <summary>
    /// 添加错误码服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configure">配置选项</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddErrorCodes(
        this IServiceCollection services,
        Action<ErrorCodeOptions> configure)
    {
        // 注册配置
        services.Configure(configure);

        // 注册错误码提供者
        services.AddSingleton<IErrorCodeProvider, DefaultErrorCodeProvider>();

        // 注册错误码初始化器
        services.AddHostedService<ErrorCodeInitializer>();

        return services;
    }
}